package com.hundsun.cprs.yyt.service.mq;


import com.hundsun.cprs.yyt.service.trade.domain.TradeCancelFlow;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessageListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.alibaba.fastjson.JSON;
import com.hundsun.cprs.yyt.service.match.dto.EntrustRequest;
import com.hundsun.cprs.yyt.service.match.service.TradeMatchInnerService;
import com.hundsun.cprs.yyt.service.rabbit.RoutingKeyConstants;
import com.hundsun.cprs.yyt.service.trade.domain.TradeEntrust;
import com.hundsun.cprs.yyt.service.trade.domain.TradeRollbackFlow;

@Component
public class TradeEntrustListener implements MessageListener {
    private static Log logger = LogFactory.getLog(TradeEntrustListener.class);
    @Autowired
    private TradeMatchInnerService tradeMatchService;
    
    @Override
    public void onMessage(Message message) {
        String routingKey = message.getMessageProperties().getReceivedRoutingKey();
        
        if (RoutingKeyConstants.YYT_TRADE_ENTRUST_COMMIT.equals(routingKey)) {
            try {
                TradeEntrust tradeEntrust = JSON.parseObject(new String(message.getBody()), TradeEntrust.class);
                if (logger.isDebugEnabled()) {
                    logger.debug("委托单上报通知:" + JSON.toJSONString(tradeEntrust));
                }
                
                EntrustRequest request = new EntrustRequest();
                request.setId(tradeEntrust.getId());
                request.setStockCode(tradeEntrust.getGoodsCode());
                tradeMatchService.handleEntrust(request);
            } catch (Exception e) {
                logger.error("委托单上报处理异常",e);
            }
        }
        
        if (RoutingKeyConstants.YYT_TRADE_ENTRUST_ROLLBACK.equals(routingKey)) {
            try {
                TradeRollbackFlow applyRollback = JSON.parseObject(new String(message.getBody()), TradeRollbackFlow.class);
                if (logger.isDebugEnabled()) {
                    logger.debug("委托单撤回通知:" + JSON.toJSONString(applyRollback));
                }
                tradeMatchService.rollbackEntrust(applyRollback);
            } catch (Exception e) {
                logger.error("委托单撤回处理异常",e);
            }
        }

        if (RoutingKeyConstants.YYT_TRADE_ENTRUST_CANCEL.equals(routingKey)) {
            try {
                TradeCancelFlow cancelFlow = JSON.parseObject(new String(message.getBody()), TradeCancelFlow.class);
                if (logger.isDebugEnabled()) {
                    logger.debug("委托单撤单通知:" + JSON.toJSONString(cancelFlow));
                }
                tradeMatchService.cancelEntrust(cancelFlow);
            } catch (Exception e) {
                logger.error("委托单撤回处理异常",e);
            }
        }
        
    }

}
